package wordit;

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Game {

	private int numOfRows;
	private int numOfColumns;
	private List<Letter> letters;

	public Game(String configFilename) throws IOException {
		Properties props = new Properties();
		props.load(new FileReader(configFilename));

		numOfRows = getIntegerProperty(props, "Rows");
		numOfColumns = numOfRows = getIntegerProperty(props, "Columns");
		letters = parseLetters(Arrays.asList(props.getProperty("Letters", "")
				.split(" ")));
	}

	private List<Letter> parseLetters(List<String> letterStrings) {
		List<Letter> letters = new ArrayList<Letter>(letterStrings.size());

		for (String str : letterStrings) {
			String[] pair = str.split(":");
			if (pair.length != 2)
				throw new IllegalArgumentException(
						"invalid letter format. Expecting \"char:value\"");

			char chr;
			int score;

			chr = pair[0].charAt(0);
			try {
				score = Integer.parseInt(pair[1]);
			} catch (NumberFormatException ex) {
				throw new IllegalArgumentException(
						"invalid score. Expecting an integer", ex);
			}

			Letter newLetter = new Letter();
			newLetter.setLetter(chr);
			newLetter.setValue(score);

			letters.add(newLetter);
		}

		return letters;
	}

	private int getIntegerProperty(Properties props, String propertyName) {
		int i;
		String str;

		str = props.getProperty(propertyName);
		if (str == null)
			throw new IllegalArgumentException(propertyName + " not defined");

		try {
			i = Integer.parseInt(str);
		} catch (NumberFormatException ex) {
			throw new IllegalArgumentException(propertyName
					+ " must be an integer", ex);
		}

		return i;
	}

	public int getNumOfRows() {
		return numOfRows;
	}

	public int getNumOfColumns() {
		return numOfColumns;
	}

	public List<Letter> getLetters() {
		return letters;
	}
}
